package org.darkforest.merchant.utils.alioss;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * Created by chenyu on 15/1/29.
 * 阿里云OSS文件上传工具，提供常用方法的封装
 * TODO ACCESS_ID,ACCESS_KEY后续需要以加密方式存入数据库中，此处直接读取，不做明文配置
 *
 */
public class OssUploadFileUtil {
    private static final String ACCESS_ID = "OmNrbdLLay3dRWq0";
    private static final String ACCESS_KEY = "clisGnrj38soYlQb2BZ9PPIHnvxNdU";
    public static String endPoint = "http://oss-cn-beijing.aliyuncs.com/";

    // 上传文件
    private static void uploadFile(OSSClient client, String bucketName, String key, File file)
            throws OSSException, ClientException, FileNotFoundException {
//        File file = new File(filename);

        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(file.length());
        // 可以在metadata中标记文件类型
        objectMeta.setContentType("image/jpeg");

        InputStream input = new FileInputStream(file);
        client.putObject(bucketName, key, input, objectMeta);
    }

    // 下载文件
    private static void downloadFile(OSSClient client, String bucketName, String key, String filename)
            throws OSSException, ClientException {
        client.getObject(new GetObjectRequest(bucketName, key),
                new File(filename));
    }

    //web端上传文件使用
    private static void postFile(OSSClient client, String bucketName, String key, String filename)
            throws OSSException, ClientException, FileNotFoundException {

    }

    public static void postFileOnWeb(){

        String bucketName = "bwmall-develop";

        // 使用默认的OSS服务器地址创建OSSClient对象。
        OSSClient client = new OSSClient(endPoint,ACCESS_ID, ACCESS_KEY);
        try {
//            setBucketPublicReadable(client, bucketName);

            System.out.println("正在上传...");
//            uploadFile(client, bucketName, key, uploadFilePath);

            System.out.println("正在下载...");
//            downloadFile(client, bucketName, key, downloadFilePath);
        } finally {
//            deleteBucket(client, bucketName);
        }
    }
}
